const express = require('express')

const app = express()
app.use(express.urlencoded())
app.use(express.json())
//创建中间件函数
let cors = (req,res,next)=>{
   
    let arr = ["http://127.0.0.1:5500","http://127.0.0.1:5501","http://127.0.0.1:5501"]
    if(arr.includes(req.headers.origin)){
        res.set("Access-Control-Allow-Origin",req.headers.origin)
        res.set("Access-Control-Allow-Headers","*")
    }
    
    next()
}
app.use(cors)

app.get('/axios/cors',(request,response)=>{
    
    setTimeout(() => {
        let body =request.query.userId
    
    if(body!=='001'){
       return response.send("失败")
    }
    response.send('成功')
    }, 5000);
    
})
app.get('/axios/get',(request,response)=>{
    setTimeout(() => {
        // let query = request.query.name
    if(!request.headers.token){
        return response.send({
            code:403,
            msg:'没有权限',
            data:null
        })
    }
    
    if(request.query.userId!=='001'){
        return response.send({
            code:404,
            msg:'请求失败',
            data:null
        })
    }
    // if(query!=='001'){
    //    return response.send("失败")
    // }
    response.send({
        code:200,
        msg:'请求成功',
        data:{
            name:'兰',
            age:18,
            sex:'男'
        }
    })
    }, 3000);
    
})
app.post('/axios/post',(request,response)=>{
    
    let body =request.body.name
    
    if(body!=='001'){
       return response.send("失败")
    }
    response.send('成功')
    
})
app.put('/axios/put',(request,response)=>{
    console.log(request.body);
    let body =request.body.name
    // console.log(body,'body');
    if(body!=='001'){
       return response.send("失败")
    }
    response.send('成功')
    
})
app.delete('/axios/delete',(request,response)=>{
    let query = request.query.name
    if(query!=='001'){
       return response.send("失败")
    }
    response.send('成功')
    
})
// app.all("/axios",(request,response)=>{
// response.setHeader("Access-Control-Allow-Origin",'*')
//     response.setHeader("Access-Control-Allow-Headers",'*')
//     let query = request.query.name
//     console.log(query);
//     if(query!=='001'){
//        return response.send("失败")
//     }
//     response.send('成功')
// })
app.get('/1',(request,response)=>{
    response.sendFile(__dirname+'/1-axios基础使用.html')
})
app.get('/2',(request,response)=>{
    response.sendFile(__dirname+'/2-axios的别名.html')
})
app.get('/3',(request,response)=>{
    response.sendFile(__dirname+'/3-axios请求拦截器.html')
})
app.get('/4',(request,response)=>{
    response.sendFile(__dirname+'/4-请求数据的处理.html')
})
app.get('/5',(request,response)=>{
    response.sendFile(__dirname+'/5-取消请求.html')
})
app.listen(8090)